package com.younio.local.compnent;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Objects;

/**
 * @desc:
 * @author: lan     [1728209643@qq.com]
 * @date: 14:32
 */
@Component
@SuppressWarnings("unchecked")
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext appContext) throws BeansException {
        applicationContext = appContext;
    }

    public static AutowireCapableBeanFactory getAutowireCapableBeanFactory() {
        return applicationContext.getAutowireCapableBeanFactory();
    }

    public static <T> T getBean(Class<T> cls) {
        return NonNull(applicationContext).getBean(cls);
    }

    public static Object getBean(String name) {
        return NonNull(applicationContext).getBean(name);
    }

    public static Map getBeansOfType(Class cls) {
        return NonNull(applicationContext).getBeansOfType(cls);
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotation) {
        return NonNull(applicationContext).getBeansWithAnnotation(annotation);
    }

    private static ApplicationContext NonNull(ApplicationContext applicationContext) {
        return Objects.requireNonNull(applicationContext, "SpringContextHolder初始化失败");
    }

    public static ApplicationContext getApplicationContext() {
        return Objects.requireNonNull(applicationContext, "SpringContextHolder初始化失败");
    }
}
